package com.dhp.bkOjquestionservice.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dhp.bkOjfeignclient.service.JudgeFeignClient;
import com.dhp.bkOjfeignclient.service.userFeignClient;
import com.dhp.bkOjquestionservice.mapper.QuestionSubmitMapper;
import com.dhp.bkOjquestionservice.rabbitMQ.MessageProducer;
import com.dhp.bkOjquestionservice.service.QuestionService;
import com.dhp.bkOjquestionservice.service.QuestionSubmitService;
import com.dhp.common.ErrorCode;
import com.dhp.constant.CommonConstant;
import com.dhp.constant.MQConstant;
import com.dhp.exception.BusinessException;
import com.dhp.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.dhp.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.dhp.model.entity.Question;
import com.dhp.model.entity.QuestionSubmit;
import com.dhp.model.entity.User;
import com.dhp.model.enums.QuestionSubmitLanguageEnum;
import com.dhp.model.enums.QuestionSubmitStatusEnum;
import com.dhp.model.vo.QuestionSubmitVO;
import com.dhp.model.vo.QuestionVO;
import com.dhp.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author Dhp
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2024-05-18 20:46:35
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService {


    @Resource
    private QuestionService questionService;

    @Resource
    private userFeignClient userFeignClient;

    @Resource
    @Lazy
    private JudgeFeignClient judgeFeignClient;

    @Resource
    private MessageProducer messageProducer;

    /**
     * 提交题目
     * @param questionSubmitAddRequest
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, Long userId) {
        //todo 加锁保证接口的幂等性，使用户无法同一时间同时提交多个提交记录
        // 判断实体是否存在，根据类别获取实体
        Long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }

        //判断编程语言是否合法
        QuestionSubmitLanguageEnum language = QuestionSubmitLanguageEnum.getEnumByValue(questionSubmitAddRequest.getLanguage());
        if (language == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR , "编程语言不合法");
        }

        QuestionSubmit questionSubmit = new QuestionSubmit();
        BeanUtil.copyProperties(questionSubmitAddRequest , questionSubmit);
        questionSubmit.setUserId(userId);
        //设置提交记录的状态为等待中
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());

        //将记录插入数据库
        boolean save = this.save(questionSubmit);
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR , "提交失败");
        }
        //同时更新题目的提交数
        question.setSubmitNum(question.getSubmitNum() + 1);
        boolean update = questionService.updateById(question);
        if (!update){
            throw new BusinessException(ErrorCode.OPERATION_ERROR , "题目信息更新失败");
        }
        long submitId = 0;
        messageProducer.sendMessage(MQConstant.EXCHANGE_NAME , MQConstant.ROUTING_KEY , JSONUtil.toJsonStr(questionSubmit));
        //QuestionSubmit questionSubmitRes = judgeFeignClient.doJudge(questionSubmit);
        return submitId;
    }



    /**
     * 获取查询包装类（用户根据哪些字段查询，根据前端传来的请求对象，得到 mybatis 框架支持的查询 QueryWrapper 类）
     *
     * @param questionSubmitQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status) != null, "status", status);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        Question relatedQuestion = questionService.getById(questionSubmit.getQuestionId());
        questionSubmitVO.setQuestion(QuestionVO.objToVo(relatedQuestion));
        // 脱敏：仅本人和管理员能看见自己（提交 userId 和登录用户 id 不同）提交的代码
        long userId = loginUser.getId();
        // 处理脱敏
        if (userId != questionSubmit.getUserId() && !userFeignClient.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null);
        }
        return questionSubmitVO;
    }


    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage, User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;
        }
        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> getQuestionSubmitVO(questionSubmit, loginUser))
                .collect(Collectors.toList());
        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }

}




